package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.ChatGridViewAdapter;
import com.hcb.tonguetiphealth.adapter.ChatListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.SmileyParser;
import com.hcb.tonguetiphealth.model.Chat;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.AbstractActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HomepageChatWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "HomepageChatWidget";
	private String url_requestChat = Global.URL + Global.servlet_requestChat;
	private String url_checkChat = Global.URL + Global.servlet_checkChat;
	private String url_sendMsg = Global.URL + Global.servlet_sendMsg;
	private String url_receiveMsg = Global.URL + Global.servlet_receiveMsg;
	
	private Activity ctx;
	private Handler mHandler;
	private LinearLayout ll_back;
	private Button bt_addicon, bt_addpicture, bt_send;
	private EditText et_content;
	private TextView chatInfo;
	private ListView listView;
	private ChatListAdapter adapter;
	private String chatID;
	private List<Chat> chatList;
	private boolean processing = false;
	private PopupWindow myPopupWindow;
	
	private long lastChatTime = 0;
	
	public HomepageChatWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.homepage_personal_chat, this); 
		//Global.homepageChatWidget = this;
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在请求聊天...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					break;
				case MessageWhat.PICTURE:
					System.out.println("-----------图片地址 " + (String)msg.obj);
					Chat chat = new Chat();
					chat.setMsg((String)msg.obj);
					chat.setPotraitURL(Global.user.getImgUrl());
					chat.setUserName(Global.user.getUserName());
					adapter.addMessage(chat);
					break;
				case MessageWhat.CHAT_RECEIVED:
					adapter.addMessages(chatList);
					break;
				}
			}
		};
		chatInfo = (TextView)findViewById(R.id.homepage_personal_chat_info_textview);
		listView = (ListView)findViewById(R.id.homepage_personal_chat_listview);
		bt_addicon = (Button)findViewById(R.id.homepage_personal_chat_add_icon_button);
		bt_addpicture = (Button)findViewById(R.id.homepage_personal_chat_add_picture_button);
		bt_send = (Button)findViewById(R.id.homepage_personal_chat_send_button);
		et_content = (EditText)findViewById(R.id.homepage_personal_chat_content_edittext);
		ll_back = (LinearLayout)findViewById(R.id.homepage_personal_chat_back_button);
		bt_addicon.setOnClickListener(this);
		//bt_addpicture.setOnClickListener(this);
		bt_send.setOnClickListener(this);
		ll_back.setOnClickListener(this);
		
		initData();
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.homepage_personal_chat_add_icon_button:
			//关闭软键盘
			InputMethodManager imm = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0);
			myPopupWindow.showAsDropDown(bt_addicon, 0, 20);
			break;
		case R.id.homepage_personal_chat_add_picture_button:
			AbstractActivity.setHandler(mHandler);
			Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
            ctx.startActivityForResult(intent, MessageWhat.PICTURE); 
			break;
		case R.id.homepage_personal_chat_send_button:
			if(et_content.getText().toString().length() != 0){
				//adapter.addMessage(new MessageInfo(DicqConstant.DEFAULTMAC,edit.getText().toString(),DicqConstant.prortait));
				/*Chat chat = new Chat();
				chat.setMsg(et_content.getText().toString());
				chat.setPotraitURL(Global.user.getImgUrl());
				adapter.addMessage(chat);
				et_content.setText(null);*/
				
				if(StringUtils.isEmpty(chatID)) {
					requestChat();
					chatInfo.setText("[系统提示]对话请求已经发送，请等待对方接受..");
					chatInfo.setVisibility(TextView.VISIBLE);
				} else {
					sendMsg(et_content.getText().toString());
					chatInfo.setVisibility(TextView.GONE);
					Chat chat = new Chat();
					chat.setMsg(et_content.getText().toString());
					chat.setPotraitURL(Global.user.getImgUrl());
					chat.setUserName(Global.user.getUserName());
					adapter.addMessage(chat);
					et_content.setText(null);
				}
			} else {
				showMessage(ctx, "不能发送空消息");
			}
			break;
		case R.id.homepage_personal_chat_back_button:
			ctx.setContentView(new HomepagePersonalWidget(ctx));
			break;
		default:
			break;
		}
	}
	private void initData() {
		chatList = new ArrayList<Chat>();
		
		adapter = new ChatListAdapter(ctx);
		listView.setAdapter(adapter);
		
		// 初始化表情解析器（将文本解析为表情图标显示，如[微笑] 显示微笑图标）
	    SmileyParser.init(ctx);
		setPopupWindow();
		
		receiveMsg();
	}
	/**
	 * 请求对话
	 */
	private void requestChat() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("targetName", "hdlihao"));
					params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
					response = HttpUtils.Post(url_requestChat, params);
					
					if(Global.DEBUG) {
						System.out.println("requestChat -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						try {
							JSONObject jo = new JSONObject(response) ;
							chatID = getString(jo, "results");
							System.out.println("chatID " + chatID);
						} catch (Exception e) {
							Log.e(TAG, "requestChat", e);
						}
						
						
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	/**
	 * 发送消息
	 * @param message
	 */
	private void sendMsg(final String message) {

		processing = true;
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("tagName", "hdlihao"));
					params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
					params.add(new BasicNameValuePair("chatId", chatID));
					params.add(new BasicNameValuePair("message", message));
					response = HttpUtils.Post(url_sendMsg, params);
					
					if(Global.DEBUG) {
						System.out.println("requestChat -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	/**
	 * 接收消息
	 */
	private void receiveMsg() {
		new Thread() {
			public void run() {
				while(Global.running) {
					String response = null;
					if(processing) {
						try {
							List <NameValuePair> params = new ArrayList <NameValuePair>();
							params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
							params.add(new BasicNameValuePair("tagName", "hdlihao")); 
							params.add(new BasicNameValuePair("chatId", chatID));
							params.add(new BasicNameValuePair("time", lastChatTime==0? 
									System.currentTimeMillis()/1000 +"" : lastChatTime +""));
							response = HttpUtils.Post1(url_receiveMsg, params);
							
							if(Global.DEBUG) {
								System.out.println("receiveMsg -----------------------------\n" + response);
							}
						} catch(Exception e) {
							Log.e(TAG, "Exception", e); 
						}
						if(!StringUtils.isEmpty(response)) {
							JSONManager jManager = new JSONManager();
							boolean isGotJSONObject = jManager.isGotJSONObject(response);
							if(isGotJSONObject) {
								JSONArray jsonList = jManager.getJsonList();
								if(jsonList != null && jsonList.length() > 0) {
									chatList.clear();
									JSONObject json;
									for(int i=0; i<jsonList.length(); i++) {
										json = getJSONObject(jsonList, i);
										Chat chat = new Chat();
										chat.setMsg(getString(json, "word"));
										chat.setPotraitURL(Global.user.getImgUrl());
										chat.setUserName(getString(json, "name"));
										lastChatTime = StringUtils.parseLong(getString(json, "time"));
										chatList.add(chat);
										mHandler.sendEmptyMessage(MessageWhat.CHAT_RECEIVED);
									}
								}
								int count = jManager.getResult();
								String msg = jManager.getMsg();
								System.out.println("------ 得到msg: " + count + ":" + msg);
							}
						}
					}
					
					try {
						Thread.sleep(6000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}
			}
		}.start();
	}
	/**展示window*/
	 private void setPopupWindow(){
			GridView gridView = new GridView(ctx);
			ChatGridViewAdapter adapter = new ChatGridViewAdapter(ctx);
			gridView.setAdapter(adapter);
			gridView.setNumColumns(6);
			gridView.setBackgroundColor(Color.rgb(214, 211, 214));
			gridView.setHorizontalSpacing(1);
			gridView.setVerticalSpacing(1);
			gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
			gridView.setGravity(Gravity.CENTER);
			gridView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					 myPopupWindow.dismiss();
					CharSequence convertContent = SmileyParser.getInstance()
					.addSmileySpans(SmileyParser.mSmileyTexts[arg2]);
					//et_content.setText(convertContent);
					et_content.append(convertContent);
					et_content.setSelection(et_content.getText().length());
				}
			});
			myPopupWindow= new PopupWindow(gridView, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT, true);
		    //myPopupWindow = new PopupWindow(gridView,LayoutParams.FILL_PARENT,350, true);//LayoutParams.WRAP_CONTENT
			myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			myPopupWindow.setAnimationStyle(R.style.PopupAnimation_buttom);
		 // myPopupWindow.showAtLocation(findViewById(R.id.rlayout), Gravity.LEFT| Gravity.LEFT, 0, 0);
			myPopupWindow.update();//更新当前状态，比如展开或者关闭等等
			 
	 }
	
	@Override
	public void notifyAdapter() {
		
	}
}
